using System;
using PEMath;
using UnityEngine;

/****************************************************
// 功能：技能
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/27 20:43:23
*****************************************************/

public class Skill
{
    public int skillId;
    public SkillConfig config;
    public PEVector3 skillArgs;
    public MainLogicUnit owner;
    public MainLogicUnit lockTarget;
    public SkillState skillState = SkillState.None;
    // 施法时间
    public PEInt spellTime;
    // 技能总时间
    public PEInt skillTime;

    public Action FreeAniCallback;

    public Action<Skill> SpellSuccessCallback;

    public int TempSkillId { set; get; }

    public Skill(int skillId, MainLogicUnit owner)
    {
        this.skillId = skillId;
        this.owner = owner;
        
        config = ResourceManager.Instance.GetSkillConfigById(skillId);
        spellTime = config.spellTime;
        skillTime = config.skillTime;

        if (config.isNormalAttack)
        {
            owner.InitAttackSpeedRate(1000 / skillTime);
        }
    }


    /// <summary>
    /// 技能释放
    /// </summary>
    /// <param name="skillArgs"></param>
    public void ReleaseSkill(PEVector3 skillArgs)
    {
        this.skillArgs = skillArgs;
        // 目标技能，必须存在施法目标，且目标队伍类型不能为动态类型
        if (config.targetCfg != null && config.targetCfg.targetTeam != TargetTeamEnum.Dynamic)
        {
            lockTarget = CalcRule.FindSingleTargetByRule(owner, config.targetCfg, skillArgs);

            if (lockTarget != null)
            {
                var dir = lockTarget.LogicPos - owner.LogicPos;
                SkillSpellStart(dir);

                /*void SkillWork() {
                    CalcSkillAttack(lockTarget);
                    AttachSkillBuffToCaster();
                    SkillSpellAfter();
                }*/
                if (spellTime == 0)
                {
                    Debug.Log("瞬发技能，立即生效");
                    SkillWork(lockTarget);
                }
                else
                {
                    
                    //lockTarget = CalcRule.FindSingleTargetByRule(owner, config.targetCfg, skillArgs);
                    /*void DelaySkillWork() {
                        if(lockTarget != null) {
                            
                            SkillWork(lockTarget);
                        }
                        else {
                            
                            SkillEnd();
                        }
                    }*/

                    // 定时处理
                    owner.CreateLogicTimer(DelaySkillWork, spellTime);
                }
            }
            else
            {
                Debug.LogWarning("没有找到符合条件的技能目标");
                SkillEnd();
            }
        }
        else
        {
            // 非目标技能
            SkillSpellStart(skillArgs);

            // 非目标弹道技能
            void DirectionBullt()
            {
                var bullet = owner.CreateSkillBullet(owner, null, this) as DirectionBullet;
                if (bullet == null) return;
                bullet.hitTargetCB = HitTarget;

                bullet.ReachPosCB = () => { Debug.Log("子弹到达了最终位置"); };
                
                
            }

            void SkillReuse()
            {
                if (config.bulletCfg != null)
                {
                    DirectionBullt();
                }
                AttachSkillBuffToCaster();
                SkillSpellAfter(); 
            }
            
            if (spellTime == 0)
            {
                SkillReuse();
            }
            else
            {
                owner.CreateLogicTimer(SkillReuse, spellTime);
            }
        }
    }

    private void SkillWork(MainLogicUnit lockTarget) {
        CalcSkillAttack(lockTarget);
        AttachSkillBuffToCaster();
        SkillSpellAfter();
    }
    
    private void DelaySkillWork() {
        //Debug.Log("第二次技能释，技能ID:" + skillId + " ，前摇时间： " + spellTime);
        if(lockTarget != null) {
                            
            SkillWork(lockTarget);
        }
        else {
                            
            SkillEnd();
        }
    }

    /// <summary>
    /// 相关buff效果实现
    /// </summary>
    private void AttachSkillBuffToCaster()
    {
        if (config.buffIDArr == null) { return; }

        for (int i = 0; i < config.buffIDArr.Length; i++)
        {
            int buffId = config.buffIDArr[i];
            if (buffId == 0)
            {
                Debug.LogWarning($"Skill：{config.skillId} not exist, buffId：0");
                continue;
            }

            BuffCfg buffCfg = ResourceManager.Instance.GetBuffConfigById(buffId);
            if (buffCfg.attacher == AttachTypeEnum.Caster || buffCfg.attacher == AttachTypeEnum.Indie)
            {
                owner.CreateSkillBuff(owner, this, buffId);
            }
        }
    }

    /// <summary>
    /// 技能生效
    /// </summary>
    /// <param name="lockTarget"></param>
    private void CalcSkillAttack(MainLogicUnit lockTarget)
    {
        if (config.bulletCfg != null)
        {
            if (owner.CreateSkillBullet(owner, lockTarget, this) is TargetBullet bullet) bullet.HitTargetCB = HitTarget;
        }
        else
        {
            HitTarget(lockTarget);
        }
    }

    private void HitTarget(MainLogicUnit target, object[] args = null)
    {
        // 音效表现
        if (config.audio_hit != null)
        {
            target.PlayAudio(config.audio_hit);
        }

        // 可能全为buff伤害，这里为0
        if (config.damage != 0)
        {
            
            PEInt damage = config.damage;
            target.GetDamageBySkill(damage, this);
        }

        if (config.buffIDArr == null)
        {
            return;
        }
        
        for(var i = config.buffIDArr.Length - 1; i >= 0; i--) {
            var buffID = config.buffIDArr[i];
            if(buffID == 0) {
                Debug.LogWarning($"SkillId:{config.skillId} exist buffID == 0,check your buffID Configs");
                continue;
            }
            var buffCfg = ResourceManager.Instance.GetBuffConfigById(buffID);
            if(buffCfg.attacher == AttachTypeEnum.Target || buffCfg.attacher == AttachTypeEnum.Bullet) {
                target.CreateSkillBuff(owner, this, buffID, args);
            }
        }
        
    }

    /// <summary>
    /// 施法前摇开始，瞬时技能这个时间阶段为0
    /// </summary>
    /// <param name="dir"></param>
    private void SkillSpellStart(PEVector3 dir)
    {
        skillState = SkillState.SpellStart;
        if (config.audio_start != null)
        {
            owner.PlayAudio(config.audio_start);
        }

        if (dir != PEVector3.zero)
        {
            owner.mainViewUnit.UpdateSkillRotation(dir);
        }

        if (config.aniName != null)
        {
            owner.InputFakeMoveKey(PEVector3.zero);
            owner.ClearFreeAniCallback();
            owner.PlayAni(config.aniName);
            // 技能被中断或后摇被移动取消需要调用动画重置
            FreeAniCallback = () =>
            {
                owner.PlayAni("free");
            };
        }
    }

    /// <summary>
    /// 技能后摇时恢复UI方向输入
    /// </summary>
    private void SkillSpellAfter()
    {
        skillState = SkillState.SpellAfter;
        if (config.audio_work != null)
        {
            owner.PlayAudio(config.audio_work);
        }
        
        // 施法成功，消耗相应的资源
        if (owner.IsPlaySelf() && !config.isNormalAttack)
        {
            // 进入技能CD
            BattleController.Instance.EnterCdState(skillId, config.cdTime);
        }
        
        // 技能释放成功回调，提供事件给buff使用
        SpellSuccessCallback?.Invoke(this);

        if (config.aniName != null)
        {
            owner.RecoverUiInput();
        }
        
        // 启动定时器，在后摇完成后技能状态重置为None、配置的技能时间必须大于施法时间，否则就没意义
        if(skillTime > spellTime) {
            owner.CreateLogicTimer(SkillEnd, skillTime - spellTime);
        }
        else {
            SkillEnd();
        }
    }

    /// <summary>
    /// 施法后摇动作完成，角色切换到idle状态
    /// </summary>
    private void SkillEnd()
    {
        //Debug.Log("技能释放结束" + skillId);
        // 技能没有释放成功，或者可以说是没有符合条件的技能目标
        if (skillState is SkillState.None or SkillState.SpellStart)
        {
            if(owner.IsPlaySelf()) {
                if(config.targetCfg != null && config.targetCfg.targetTeam == TargetTeamEnum.Enemy && config.targetCfg.searchDis > 0) {
                    var mf = owner.GetBuffById(Constants.MOVE_ATTACK_BUFF_ID);
                    if(mf != null) {
                        mf.unitState = SubUnitState.End;
                    }

                    Debug.Log("技能未施放成功，添加通用移动攻击buff.");
                    owner.CreateSkillBuff(owner, this, Constants.MOVE_ATTACK_BUFF_ID);
                }
            }
        }
        
        if (FreeAniCallback != null)
        {
            FreeAniCallback();
            FreeAniCallback = null;
        }
        
        

        skillState = SkillState.None;
        lockTarget = null;
    }
    
    /// <summary>
    /// 技能替换
    /// </summary>
    /// <param name="replaceID"></param>
    public void ReplaceSkillCfg(int replaceID)
    {
        TempSkillId = skillId == replaceID ? 0 : replaceID;

        config = ResourceManager.Instance.GetSkillConfigById(replaceID);
        /*
        spellTime = cfg.spellTime;
        skillTime = cfg.skillTime;
        if(cfg.isNormalAttack) {
            owner.InitAttackSpeedRate(1000 / skillTime);
        }
        */
    }
}

public enum SkillState
{
    None,
    SpellStart,
    SpellAfter
}
